package org.zjx.log;

/**
 * Logger类用于记录日志，结合LogManager和LogFilter实现日志的处理。
 */
public class Logger {
    private LogManager logManager;
    private LogFilter logFilter;

    public Logger(LogManager logManager, LogFilter logFilter) {
        this.logManager = logManager;
        this.logFilter = logFilter;
    }

    /**
     * 记录日志。
     *
     * @param moduleName 模块名称
     * @param level 日志级别
     * @param message 日志消息
     */
    public void log(String moduleName, LogLevel level, String message) {
        if (logFilter.shouldLog(level, moduleName)) {
            String formattedMessage = logManager.getLogFormatter().format(level, message);
            logManager.handleLog(level, formattedMessage);
        }
    }


    public static Logger logger;

    public static Logger getLogger() {
        if (logger == null) {
            // 创建日志管理器
            LogManager logManager = new LogManager();

            // 设置日志级别
            logManager.setLogLevel(LogLevel.DEBUG);

            // 添加日志轮转处理器
            logManager.addLogHandler(new LogRotationHandler("game_logs.txt"));

            // 添加异步日志处理器
            logManager.addLogHandler(new AsynchronousLogHandler(new ConsoleLogHandler()));
            logManager.addLogHandler(new AsynchronousLogHandler(new FileLogHandler("日志.txt")));

            // 创建日志过滤器
            LogFilter logFilter = new LogFilter(LogLevel.DEBUG);
            logFilter.addEnabledModule("GameModule");
            logFilter.addEnabledModule("RequestInterceptor");
            logFilter.addEnabledModule("ResponseInterceptor");
            logFilter.addEnabledModule("DownloadTask");


            // 创建日志记录器
            logger = new Logger(logManager, logFilter);

            // 输出日志
            logger.log("GameModule", LogLevel.INFO, "Game started.");
            logger.log("GameModule", LogLevel.DEBUG, "Debugging game mechanics.");
            logger.log("OtherModule", LogLevel.INFO, "Other module log.");
            return logger;
        }else return logger;
    }
}

